package com.dure.hotmemory.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.dure.hotmemory.R;


/**
 * Created by leix on 10/3/16.
 */

public class CircleImageView extends View {
    Bitmap bitmap;
    float radius;
    Paint paint, circlePaint;

    public CircleImageView(Context context) {
        super(context);
        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);

        circlePaint = new Paint();
        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setAntiAlias(true);
        circlePaint.setColor(Color.WHITE);

        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        radius = getWidth() / 2;
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;


        Bitmap tempBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas temCanvas = new Canvas(tempBitmap);
        temCanvas.drawCircle(centerX, centerY, radius, paint);


        if (bitmap != null) {
            Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            RectF dstRect = new RectF(0, 0, getWidth(), getHeight());

            Paint bitmapPaint = new Paint();
            bitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

            temCanvas.drawBitmap(bitmap, srcRect, dstRect, bitmapPaint);
        }


        canvas.drawBitmap(tempBitmap, 0, 0, null);

        canvas.drawCircle(centerX, centerY, radius, circlePaint);


    }


    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        invalidate();
    }
}
